package risk.rest.rcv.security

import org.springframework.web.method.support.HandlerMethodArgumentResolver
import org.springframework.core.MethodParameter
import org.springframework.web.method.support.ModelAndViewContainer
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.bind.support.WebDataBinderFactory
import edu.fudan.langlab.domain.security.User
import org.springframework.web.context.request.RequestAttributes
import org.springframework.beans.factory.annotation.Autowired;
import edu.fudan.mylang.pf.IObjectFactory
import org.springframework.web.multipart.support.MissingServletRequestPartException
import org.springframework.stereotype.Component

@Component
class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IObjectFactory objectFactory;

    override boolean supportsParameter(MethodParameter parameter) {
        if (parameter.getParameterType().isAssignableFrom(User) &&
                parameter.hasParameterAnnotation(CurrentUser)) {
            return true;
        }
        return false;
    }

    override Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        val Long currentUserId =  webRequest.getAttribute("__current_user_id__", RequestAttributes.SCOPE_REQUEST) as Long;
        if (currentUserId != null) {
            return objectFactory.<User>get(User,currentUserId)
        }
        throw new MissingServletRequestPartException("CurrentUser");
    }
    

    
    
}
